const request = require('request')
const express = require('express')
const router = express.Router()
const path = require('path')
const useDb = require(path.join(global.initUrl, 'mongodb/index')).use

//获取用户apenIp接口
router.get('/login', function (req, res, next) {
    req.query.secret = global.secret
    req.query.appid = global.appid
    request({
        method: 'get',
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        qs: req.query
    }, async function (req1, res1, body) {
        const info = JSON.parse(body)
        var nu = await useDb.countDocuments({ openid: info.openid })
        /*useDb.find({}, function (err, data) {
            console.log(data)
        })*/
        if (nu !== 0) {
            res.cookie('tonke', info.openid, { maxAge: 600000 })
            res.send({
                state: 'OK'
            })
        } else {
            useDb.create(info, function (err, data) {
                if (err) {
                    res.send({
                        err: '登录失败',
                        state: 'NO'
                    })
                } else {
                    res.cookie('tonke', info.openid, { maxAge: 600000, signed: true })
                    res.send({
                        state:'OK'
                    })
                }
            })
        }
    })
})

module.exports = router;